package NetWork;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Vector;

import NetWork.SocketConnector;

public class SocketServerUtil extends Thread
{
	private int									port;
	private ServerSocket						server;
	private Hashtable<String, SocketConnector>	connectorTable;
	public Vector<NetWorkDelegate>				delegateVector;
	private boolean keepAlive;

	public SocketServerUtil(int portNumber,
			Hashtable<String, SocketConnector> table)
	{
		port = portNumber;
		connectorTable = table;
		keepAlive = true;
		try
		{
			server = new ServerSocket(port);
			System.out.printf("Start listening on port %d\n", port);
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			port = portNumber+1000;
			try
			{
				server = new ServerSocket(port);
				TransmissionUtil.listeningPort = port;
				System.out.printf("Start listening on port %d\n", port);
			}
			catch (IOException e1)
			{
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}

	public SocketConnector getConnectorByAddr(String host, int port)
	{
		return connectorTable.get(String.format("%s:%d", host, port));
	}
	public void closeSever()
	{
		keepAlive = false;
	}

	public void run()
	{
		while (keepAlive)
		{
			try
			{
				//synchronized (server)
				{
					Socket s = server.accept();
					System.out.printf("server is listening on %d\n", server.getLocalPort());
					String addr = String.format("%s:%d", s.getInetAddress().getHostAddress(), s.getPort());
					System.out.printf("%s connected!\n", addr);

					SocketConnector connector = new SocketConnector(s);
					connectorTable.put(addr, connector);
					connector.start();
					//System.out.printf("connectorTalbe add %s\n", addr);
				}
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				keepAlive =false;
				e.printStackTrace();
			}
		}
	}
}
